package com.guo.mixframe.framework.io

import java.util.concurrent.locks.ReentrantReadWriteLock

/**
 * @author  gx
 * @description 配置加载基类
 */
abstract class Loader {

  val lock = ReentrantReadWriteLock()
  val readLock: ReentrantReadWriteLock.ReadLock = lock.readLock()
  val writeLock: ReentrantReadWriteLock.WriteLock = lock.writeLock()


  /**
   * 加载配置的抽象函数,子类getInstance被调用
   */
  abstract fun reload()

  /**
   * 使用读锁
   */
  fun <T> useReadLock(action: () -> T) : T {
    readLock.lock()
    return try {
      action()
    } finally {
      readLock.unlock()
    }
  }

  /**
   * 使用写锁
   */
  fun useWriteLock(action:() -> Unit){
    writeLock.lock()
    try {
        action()
    }finally {
        writeLock.unlock()
    }
  }

  companion object{
    /**
     *  子类直接调用实例化方法，返回子类的实例
     */
    fun <T : Loader> getInstance(instance : T?,cls:Class<T>):T{
      if(instance != null){
          return instance
      }
      val tempInstance = cls.getConstructor().newInstance()
      //加载配置表数据
      tempInstance.reload()
      //将实例注册到readerManager中,可用于刷表是便利
      LoaderManager.register(cls.simpleName,tempInstance)
      return tempInstance
    }
  }


}
